package com.example.smart.controller;

import com.example.common.util.R;
import com.example.smart.service.DynamicService;
import com.example.item.Dynamic;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/dynamic/")
@Tag(name = "显示动态数据")
public class DynamicController {
    @Autowired
    private DynamicService dynamicService;

    @PreAuthorize("hasAuthority('dynamic:list')")
    @Operation(summary = "获得所有的动态数据")
    @GetMapping(value = "/getAllDynamic")
    public R getAllDynamic() {
        List<Dynamic> dynamicList = dynamicService.list();
        return R.ok("查询所有动态数据成功").data("dynamicList", dynamicList);
    }

    @PreAuthorize("hasAuthority('dynamic:add')")
    @Operation(summary = "增加动态")
    @PostMapping(value = "/addDynamic")
    public R addDynamic(@RequestBody Dynamic dynamic) {
        boolean flag = dynamicService.save(dynamic);
        if (flag) {
            return R.ok("增加动态成功");
        } else {
            return R.error("增加动态失败");
        }
    }

    @PreAuthorize("hasAuthority('dynamic:delete')")
    @Operation(summary = "删除动态数据")
    @DeleteMapping(value = "/deleteDynamic/{id}")
    public R deleteDynamic(@PathVariable("id") Integer dynamicId) {
        boolean flag = dynamicService.removeById(dynamicId);
        if (flag) {
            return R.ok("删除动态成功");
        } else {
            return R.error("删除动态失败");
        }
    }

    @PreAuthorize("hasAuthority('dynamic:getById')")
    @Operation(summary = "按照动态编号查询数据")
    @GetMapping(value = "/getDynamicById/{id}")
    public R getByIdDynamic(@PathVariable("id") Integer dynamicId) {
        Dynamic dynamic = dynamicService.getById(dynamicId);
        return R.ok("按照动态编号查询数据成功").data("dynamic", dynamic);
    }

    @PreAuthorize("hasAuthority('dynamic:update')")
    @Operation(summary = "修改动态数据")
    @PutMapping(value = "/updateDynamic")
    public R updateDynamic(@RequestBody Dynamic dynamic) {
        boolean flag = dynamicService.updateById(dynamic);
        if (flag) {
            return R.ok("修改动态成功");
        } else {
            return R.error("修改动态失败");
        }
    }
}
